package cn.tedu.bigdecimal;
/**
 * @Author 金帮嘉诚  @Date 2021-06-16 周三 15:11
 */
/*本类用于解决浮点数运算不精确的问题*/

import java.math.BigDecimal;
import java.util.Scanner;

/**
 * 知识点：
 */
public class TestBigDecimal {
    public static void main(String[] args) {
        f1();//浮点数运算不精确
        f2();//浮点数运算不精确解决

    }

    private static void f1() {
        System.out.println("请输入要计算的两个小数：");
        System.out.print("1:");
        double a = new Scanner(System.in).nextDouble();
        System.out.print("2:");
        double b = new Scanner(System.in).nextDouble();
        System.out.println("(a+b) = " + (a + b));
        System.out.println("(a-b) = " + (a - b));
        System.out.println("(a*b) = " + (a * b));
        System.out.println("(a/b) = " + (a / b));

    }

    private static void f2() {
        System.out.println("请输入要计算的两个小数：");
        System.out.print("1:");
        double a = new Scanner(System.in).nextDouble();
        System.out.print("2:");
        double b = new Scanner(System.in).nextDouble();

        /*注意，这里有坑，不要使用double参数的构造方法，
        因为还是不精确的结果，要使用参数类型为String的构造方法
        double转String，直接拼个空串就可以*/
        BigDecimal bd1 = new BigDecimal(a + "");
        BigDecimal bd2 = new BigDecimal(b + "");

        BigDecimal bd3;
        bd3 = bd1.add(bd2);
        System.out.println("bd1.add(bd2) = " + bd3);
        bd3 = bd1.multiply(bd2);
        System.out.println("bd1.multiply(bd2) = " + bd3);
        bd3 = bd1.subtract(bd2);
        System.out.println("bd1.subtract(bd2) = " + bd3);
        /*由于除法会出现除不尽的现象，数据仍没办法精确展示，
        所以我们需要提前设置除不尽时保留的位数以及舍入规则*/
        bd3 = bd1.divide(bd2, 3, BigDecimal.ROUND_HALF_UP);
        System.out.println("bd3=bd1.divide() = " + bd3);

    }
}
